angular.module('furion.controllers.friends', [])

.controller 'FriendsCtrl', ($scope, $ionicActionSheet, $cordovaContacts, RemoteSrv, Config) ->

  $scope.getAllContacts = ()->
    if !furion.utils.isDevice()
      $scope.friends = [
        {name: {formatted: 'zhangwenyuan'}, phoneNumbers: [{value: '18736246309'},{value: '18739718903'}]}
      ]
      $scope.$broadcast 'scroll.refreshComplete'
      $scope.$broadcast 'scroll.infiniteScrollComplete'
    return unless furion.utils.isDevice() # 网页内不进行搜索操作

    $scope.$emit "loading:show"
      
    onSuccess = (contacts)->
      $scope.$emit "loading:hide"
      $scope.friends = contacts

      $scope.$broadcast 'scroll.refreshComplete'
      $scope.$broadcast 'scroll.infiniteScrollComplete'

    fields = [navigator.contacts.fieldType.displayName, navigator.contacts.fieldType.name]

    navigator.contacts.find(fields, onSuccess)
    
  $scope.searchF = (name)->
    return unless furion.utils.isDevice() # 网页内不进行搜索操作
    if !name
      $scope.getAllContacts()
      return
    $scope.$emit "loading:show"
      
    onSuccess = (contacts)->
      $scope.$emit "loading:hide"
      $scope.friends = contacts
      console.log contacts

    onError = (err)->
      console.debug err

    options = new ContactFindOptions()
    options.filter = name

    fields = [navigator.contacts.fieldType.displayName, navigator.contacts.fieldType.name]

    navigator.contacts.find(fields, onSuccess, onError, options)

  $scope.$on '$ionicView.enter', (event)->
    if !$scope.friends
      $scope.getAllContacts()

  $scope.telUs = (num)->
    $ionicActionSheet.show
      buttons: [{ text: '呼叫' + num }]
      titleText: '工作日: 9:30~19:00'
      cancelText: '取消',
      buttonClicked: (index)->
        window.location = "tel:" + num
    return

  return